package com.starxg.m3u8.parser;

import com.starxg.m3u8.exception.M3U8Exception;
import com.starxg.m3u8.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;

import lombok.*;

/**
 * M3U8Key
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-08-11 11:18
 */
@AllArgsConstructor
@Getter
@Setter
@ToString
@NoArgsConstructor
public class M3U8Key {
    static final String PREFIX = "#EXT-X-KEY";

    private String key;
    /**
     * 偏移量
     */
    private String iv;
    private KeyMethod method;

    @AllArgsConstructor
    @Getter
    public enum KeyMethod {
        /**
         * AES_128
         */
        AES_128("AES-128");

        private final String text;

        public static KeyMethod textOf(String text) {
            for (KeyMethod k : KeyMethod.values()) {
                if (k.getText().equalsIgnoreCase(text)) {
                    return k;
                }
            }
            throw new IllegalArgumentException(text);
        }

    }

    static M3U8Key parse(String text, M3U8 m3u8) throws Exception {
        if (StringUtils.isBlank(text)) {
            throw new IllegalArgumentException(text);
        }

        if (!text.startsWith(PREFIX)) {
            throw new IllegalArgumentException(text);
        }

        String[] keys = StringUtils.split(text, ":", 2);
        if (keys.length < 2) {
            throw new IllegalArgumentException(text);
        }

        String keyInfo = keys[1];
        String[] split = keyInfo.split(",");
        String keyMethod = StringUtils.remove(split[0], "METHOD=");
        String uri = StringUtils.remove(StringUtils.remove(split[1], "URI="), "\"");
        String iv = null;
        if (split.length > 2) {
            iv = StringUtils.remove(StringUtils.remove(split[2], "IV="), "\"");
        }
        M3U8Key key = new M3U8Key();
        try {
            key.setKey(HttpUtils.get(m3u8.absUrl(uri).toString()));
        } catch (Exception e) {
            throw new M3U8Exception("解析Key时失败。" + e.getMessage());
        }
        key.setMethod(M3U8Key.KeyMethod.textOf(keyMethod));
        key.setIv(iv);
        return key;
    }
}
